<script>
import {getAcceptAddressList} from "@/api/mall";

export default {
  name: "index",
  props: {
    // 已选择的地址（从父组件传入）
    selectedAddress: {
      type: Object,
      default: () => null
    }
  },
  data() {
    return {
      addresses: [],
      loading: true
    }
  },
  created() {
    this.init();
  },
  methods: {
    async init(){
      try {
        this.loading = true;
        const { Data } = await getAcceptAddressList({
          Index: 1,
          Size: 100,
        });
        
        if (Data && Data.length > 0) {
          // 将API返回的数据转换为组件需要的格式
          this.addresses = Data.map(item => ({
            id: item.Id,
            name: item.Name,
            phone: item.Mobile || '',
            province: item.Province,
            city: item.City,
            county: item.County,
            address: item.Address,
            isDefault: item.IsDefault === 1,
            selected: false
          }));
          
          // 初始化选中状态
          this.initSelectedState();
        } else {
          // 如果没有数据，使用空数组
          this.addresses = [];
        }
      } catch (error) {
        console.error('获取地址列表失败', error);
        uni.showToast({
          title: '获取地址列表失败',
          icon: 'none'
        });
        
        // 出错时使用空数组
        this.addresses = [];
      } finally {
        this.loading = false;
      }
    },
    
    // 初始化选中状态
    initSelectedState() {
      // 重置所有地址的选择状态
      this.addresses.forEach(address => {
        address.selected = false;
      });
      
      // 根据父组件传入的已选择地址设置选中状态
      if (this.selectedAddress) {
        const selectedId = this.selectedAddress.id;
        
        this.addresses.forEach(address => {
          if (address.id === selectedId) {
            address.selected = true;
          }
        });
      } else {
        // 如果没有传入选定地址，则选择默认地址
        const defaultAddress = this.addresses.find(address => address.isDefault);
        if (defaultAddress) {
          defaultAddress.selected = true;
        }
      }
    },
    
    // 切换选择状态
    selectAddress(address) {
      // 先取消所有地址的选中状态
      this.addresses.forEach(item => {
        item.selected = false;
      });
      
      // 设置当前地址为选中状态
      address.selected = true;
    },
    
    // 确认选择
    confirmSelection() {
      const selectedAddress = this.addresses.find(address => address.selected);
      
      if (!selectedAddress) {
        uni.showToast({
          title: '请选择一个收货地址',
          icon: 'none'
        });
        return;
      }
      
      // 发送选中的地址给父组件
      this.$emit('select', selectedAddress);
      
      // 发送完成事件
      this.$emit('complete');
    },
    
    // 添加新地址按钮点击
    onAddNewAddress() {
      // 跳转到添加地址页面
      uni.navigateTo({
        url: '/user_subpages/address/add-address',
        events: {
          // 添加完成后触发的事件
          addAddressComplete: () => {
            // 重新加载数据
            this.init();
          }
        },
        success: (res) => {
          // 监听页面返回事件
          const addAddressPage = res.eventChannel;
          // 可以向打开的页面传递数据
          addAddressPage.emit('initData', {
            from: 'selectAddress'
          });
        }
      });
    },
    
    // 编辑地址
    editAddress(address) {
      uni.navigateTo({
        url: `/user_subpages/address/edit-address?id=${address.id}`,
        events: {
          // 编辑完成后触发的事件
          editAddressComplete: () => {
            // 重新加载数据
            this.init();
          }
        }
      });
    }
  }
}
</script>

<template>
  <view class="select-address">
    <!-- 地址列表 -->
    <view class="address-list">
      <!-- 加载中状态 -->
      <view class="loading-container" v-if="loading">
        <view class="loading-item" v-for="i in 3" :key="i">
          <view class="loading-radio"></view>
          <view class="loading-info">
            <view class="loading-header">
              <view class="loading-name"></view>
              <view class="loading-phone"></view>
            </view>
            <view class="loading-addr"></view>
          </view>
          <view class="loading-edit"></view>
        </view>
      </view>
      
      <!-- 空数据状态 -->
      <view class="empty-state" v-else-if="addresses.length === 0">
        <image src="/static/empty.png" mode="aspectFit" class="empty-image"></image>
        <text class="empty-text">暂无收货地址，请添加</text>
        <view class="add-first-address" @click="onAddNewAddress">
          <text>添加地址</text>
        </view>
      </view>
      
      <!-- 地址列表 -->
      <template v-else>
        <view class="addresses">
          <view class="address-item" v-for="address in addresses" :key="address.id" @click="selectAddress(address)">
            <view class="radio" :class="{'checked': address.selected}">
              <view class="radio-inner" v-if="address.selected"></view>
            </view>
            <view class="address-info">
              <view class="address-header">
                <view class="name-container">
                  <text class="name">{{address.name}}</text>
                  <text class="default-tag" v-if="address.isDefault">默认</text>
                </view>
                <text class="phone">{{address.phone}}</text>
              </view>
              <view class="address-detail">
                {{address.province}} {{address.city}} {{address.county}} {{address.address}}
              </view>
            </view>
          </view>
        </view>
        
        <view class="select-bottom">
          <!-- 添加新地址按钮 -->
          <view class="add-address" @click="onAddNewAddress">
            <text class="add-icon">+</text>
            <text class="add-text">添加新地址</text>
          </view>
          
          <!-- 底部确认按钮 -->
          <view class="confirm-btn" @click="confirmSelection">
            <view class="btn">确定</view>
          </view>
        </view>
      </template>
    </view>
  </view>
</template>

<style scoped lang="scss">
.select-address {
  position: relative;
  background-color: #fff;
  min-height: 500rpx;
  .address-list {
    position: relative;
    .addresses {
      padding: 20rpx 30rpx 0;
      position: relative;
      height: calc(100% - 230rpx);
      overflow-y: auto;
      .address-item {
        display: flex;
        align-items: flex-start;
        padding: 30rpx 0;
        border-bottom: 1px solid #eee;
        position: relative;
        .radio {
          width: 40rpx;
          height: 40rpx;
          border-radius: 50%;
          border: 2rpx solid #ddd;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 20rpx;
          margin-top: 10rpx; 
          &.checked {
            border-color: #498fff;
          }
          .radio-inner {
            width: 24rpx;
            height: 24rpx;
            border-radius: 50%;
            background-color: #498fff;
          }
        }
        .address-info {
          flex: 1;
          .address-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15rpx;
            .name-container {
              display: flex;
              align-items: center;
              gap: 10rpx;
              .name {
                font-size: 30rpx;
                color: #333;
                font-weight: 500;
              }
              .default-tag {
                font-size: 22rpx;
                color: #498fff;
                background: rgba(73, 143, 255, 0.1);
                padding: 4rpx 10rpx;
                border-radius: 4rpx;
              }
            }
            .phone {
              font-size: 28rpx;
              color: #666;
            }
          }
          .address-detail {
            font-size: 28rpx;
            color: #666;
            line-height: 1.5;
            padding-right: 60rpx;
          }
        }
        .edit-btn {
          position: absolute;
          right: 10rpx;
          top: 30rpx;
          width: 50rpx;
          height: 50rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          
          .edit-icon {
            font-size: 36rpx;
            color: #999;
          }
        }
      }
    }

    .select-bottom {
      position: sticky;
      bottom: 0;
      left: 0;
      right: 0;
      width: 100%;
      background-color: #fff;
      box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
      .add-address {
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 30rpx 0;
        .add-icon {
          font-size: 36rpx;
          color: #498fff;
          margin-right: 10rpx;
        }
        .add-text {
          font-size: 30rpx;
          color: #498fff;
        }
      }
      .confirm-btn {
        padding: 20rpx 30rpx;
        .btn {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 100%;
          height: 90rpx;
          color: #fff;
          border-radius: 45rpx;
          font-size: 32rpx;
          background: linear-gradient(135deg, #498FFF 0%, #3A7FE6 100%);
        }
      }
    }
  }
}

/* 加载中状态样式 */
.loading-container {
  padding: 20rpx 0;
  
  .loading-item {
    display: flex;
    align-items: flex-start;
    padding: 30rpx 0;
    border-bottom: 1px solid #eee;
    position: relative;
    
    .loading-radio {
      width: 40rpx;
      height: 40rpx;
      border-radius: 50%;
      border: 2rpx solid #eee;
      margin-right: 20rpx;
      background: #f5f5f5;
      margin-top: 10rpx;
    }
    
    .loading-info {
      flex: 1;
      
      .loading-header {
        display: flex;
        justify-content: space-between;
        margin-bottom: 15rpx;
        
        .loading-name {
          height: 30rpx;
          width: 120rpx;
          background: #f5f5f5;
          border-radius: 4rpx;
        }
        
        .loading-phone {
          height: 28rpx;
          width: 150rpx;
          background: #f5f5f5;
          border-radius: 4rpx;
        }
      }
      
      .loading-addr {
        height: 28rpx;
        width: 80%;
        background: #f5f5f5;
        border-radius: 4rpx;
        margin-bottom: 10rpx;
      }
    }
    
    .loading-edit {
      position: absolute;
      right: 10rpx;
      top: 30rpx;
      width: 36rpx;
      height: 36rpx;
      border-radius: 4rpx;
      background: #f5f5f5;
    }
  }
}

/* 空数据状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80rpx 0;
  
  .empty-image {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 20rpx;
  }
  
  .empty-text {
    font-size: 28rpx;
    color: #999;
    margin-bottom: 40rpx;
  }
  
  .add-first-address {
    background: linear-gradient(135deg, #498FFF 0%, #3A7FE6 100%);
    color: #fff;
    border-radius: 45rpx;
    padding: 20rpx 60rpx;
    font-size: 30rpx;
  }
}
</style>